package com.techblor.wechat.library.util;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务器请求工具类
 */
@Slf4j
public class RequestUtil {

    /**
     * 解析请求xml输入流数据
     *
     * @param request
     * @return
     */
    public static Map<String, String> parseXml(HttpServletRequest request) {
        // 将解析结果存储在map中
        Map<String, String> map = new HashMap<>();
        InputStream inputStream = null;
        try {
            // 从request中取得输入流
            inputStream = request.getInputStream();
            SAXReader reader = new SAXReader();
            Document doc = reader.read(inputStream);
            Element root = doc.getRootElement();
            List<Element> list = root.elements();

            for (Element e : list) {
                map.put(e.getName(), e.getText());
            }
        } catch (Exception e) {
            log.error("解析xml异常: {}", e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("关闭输入流异常: {}", e.getMessage());
                }
            }
        }

        return map;
    }

}
